package com.hzy.fivepalace.admin.async;


import com.hzy.fivepalace.db.dao.DtsUserMapper;
import com.hzy.fivepalace.db.dao.ex.DtsCouponUserMapperEx;
import com.hzy.fivepalace.db.domain.DtsCouponUser;
import com.hzy.fivepalace.db.domain.DtsCouponUserExample;
import com.hzy.fivepalace.db.domain.DtsUser;
import com.hzy.fivepalace.db.domain.DtsUserExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;


/**
 * 后台管理api异步工厂（产生任务用）
 *
 * @author gejian
 */
@Service
public class AdminAsyncFactory {

    private static final Logger logger = LoggerFactory.getLogger(AdminAsyncFactory.class);

    @Resource
    private DtsCouponUserMapperEx couponUserMapperEx;

    @Resource
    private DtsUserMapper userMapper;

    /**
     * 异步派发优惠券 给所有用户
     *
     * @param couponUser
     */
    @Async
    public void asyncPayoutCouponsAll(DtsCouponUser couponUser) {
        //查询所有正常用户
        DtsUserExample example = new DtsUserExample();
        example.createCriteria().andDeletedEqualTo(false).andStatusEqualTo((byte) 0);
        List<DtsUser> userList = userMapper.selectByExample(example);
        userList.forEach(user -> {
            DtsCouponUser coupon = couponUser;
            coupon.setUserId(user.getId());
            couponUserMapperEx.insertSelective(coupon);
        });

    }

    /**
     * 异步作废已派发未使用的优惠券
     *
     * @param id
     */
    @Async
    public void asyncWithdrawAllPayout(Integer id) {
        DtsCouponUser couponUserUpd = new DtsCouponUser();
        couponUserUpd.setDeleted(true);
        couponUserUpd.setUpdateTime(LocalDateTime.now());
        DtsCouponUserExample example = new DtsCouponUserExample();
        example.createCriteria().andStatusEqualTo((short) 0).andCouponIdEqualTo(id).andDeletedEqualTo(false);
        couponUserMapperEx.updateByExampleSelective(couponUserUpd, example);

    }

}
